package cn.enjoyedu.ch01.bio.me;

import cn.enjoyedu.ch01.Ch01Const;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class BioServerHandler implements Runnable {


    private Socket socket;

    public BioServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
        ) {
            String message;
            String result;

            while ((message = in.readLine()) != null) {
                System.out.println("Server accept message" + message);
                result = Ch01Const.response(message);
                out.println(result);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket == null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }


    }
}
